import axios from 'axios'
import store from '../store'
import {
  removeLocalStorage
} from '@/assets/js/storage'
import {
  Toast,
  Dialog
} from 'vant'

const NET_WORK_STATUS = '网络错误'
const tip = (msg) => {
  Toast({
    message: msg,
    duration: 3000,
    forbidClick: true
  })
}

const errorHandle = (status, other) => {
  switch (status) {
    // 404 请求不存在
    case 404:
      tip('请求资源不存在')
      break
    case 401:
      removeLocalStorage('USER_INFO')
      removeLocalStorage('person')
      removeLocalStorage('contacts')
      removeLocalStorage('bank')
      Dialog.confirm({
        title: '登录失效',
        message: '请重新登录'
      }).then(() => {
        window.location.href = '/'
      }).catch(() => {
        window.location.href = '/'
      })
      break
    default:
      break
  }
}

// 创建拦截器
// const host = process.env.NODE_ENV === 'development' ? 'dev api host' : 'prod api host'
const instance = axios.create({
  timeout: 1000 * 10
})
// 请求头
instance.defaults.headers.post['Content-type'] = 'application/x-www-form-urlencoded'

// 每次请求有token携带Token
instance.interceptors.request.use(
  config => {
    // const token = store.state.token
    // token && (config.headers.Authorization = token)
    return config
  },
  error => Promise.error(error)
)
// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res),
  // 请求失败
  error => {
    const {
      response
    } = error
    if (response) {
      // 请求已经发出但不在2xx范围
      errorHandle(response.status, response.data.message)
      return Promise.reject(response)
    } else {
      store.commit('changeNetWork', NET_WORK_STATUS)
    }
  })
export default instance
